package co.recloud.ariadne.persistor;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import co.recloud.ariadne.model.Host;
import co.recloud.ariadne.model.logical.Column;
import co.recloud.ariadne.model.logical.Table;
import co.recloud.ariadne.model.logical.Transaction;
import co.recloud.ariadne.store.TransactionCache;

/**
 * Cassandra-thrift implementation
 * 
 * @author alex
 * 
 */
public class KeyValuePersistorImpl implements KeyValuePersistor {

	private Transaction transaction;
	
	public KeyValuePersistorImpl(Transaction transaction) {
		this.transaction = transaction;
	}
//	private Host host = null;

	public void setHost(Host host) {
//		this.host = host;
	}
	
	public String getValue(String key, Column column) {
		TransactionCache pool = TransactionCache.getInstance(transaction.getId());

		String value = pool.getString(transaction, "key_values", column.getTable().getName(), key, column.getField(), column.getTable().isResultSet());

		return value;
	}

	public void setValue(String key, Column column, String value) {
		TransactionCache pool = TransactionCache.getInstance(transaction.getId());
		pool.putColumn(transaction, "key_values", column.getTable().getName(), key, column.getField(), value);
	}

	public Set<String> getAllKeys(
			Table table) {
		TransactionCache pool = TransactionCache.getInstance(transaction.getId());
		return pool.getAllKeys(transaction, "key_values", table.getName(), table.isResultSet());
	}

	public Map<String, Object> getAllColumns(String key, Table table) {
		TransactionCache pool = TransactionCache.getInstance(transaction.getId());
		return pool.getAllColumns(transaction, "key_values", table.getName(), key, table.isResultSet());
	}

	public void dropTable(Table table) {
		TransactionCache pool = TransactionCache.getInstance(transaction.getId());
		pool.dropTable(transaction, "key_values", table.getName());
		
	}
	
	public int estimateCardinality(Table table) {
		return 10000000;
	}

	/**
	 * @param transaction the transaction to set
	 */
	public void setTransaction(Transaction transaction) {
		this.transaction = transaction;
	}

	/**
	 * @return the transaction
	 */
	public Transaction getTransaction() {
		return transaction;
	}

	public Map<String, Object> getColumns(String key, Set<Column> columns) {
		TransactionCache pool = TransactionCache.getInstance(transaction.getId());
		Map<String, Set<String>> columnNames = new HashMap<String, Set<String>>();
		Map<String, Object> result = new HashMap<String, Object>();
		for(Column column : columns) {
			String tableName = column.getTable().getName();
			if(! columnNames.containsKey(tableName)) {
				columnNames.put(tableName, new HashSet<String>());
			}
			columnNames.get(tableName).add(column.getField());
		}
		for(String tableName : columnNames.keySet()) {
			result.putAll(pool.getColumns(transaction, "key_values", tableName, key, columnNames.get(tableName)));
		}
		return result;
	}

}
